<template>
    <el-upload action="#" list-type="picture-card" :auto-upload="false">
      <el-icon>
        <Plus />
      </el-icon>
      <template #file="{ file }">
        <div>
          <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" />
          <span class="el-upload-list__item-actions">
            <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
              <el-icon><zoom-in /></el-icon>
            </span>
            <span v-if="!disabled" class="el-upload-list__item-delete" @click="handleDownload(file)">
              <el-icon>
                <Upload />
              </el-icon>
            </span>
          </span>
        </div>
      </template>
    </el-upload>
    <el-dialog v-model="dialogVisible">
      <img w-full :src="dialogImageUrl" alt="Preview Image" />
    </el-dialog>
  </template>


<script lang="ts" setup>
import { ref } from 'vue'
import { ElMessage, type UploadFile } from 'element-plus'
import { updateEmployeeAvatar } from '@/api/employee'

import { useUserStore } from '@/stores/user'

// 实例化仓库
const counterStore = useUserStore();

const dialogImageUrl = ref('')
const dialogVisible = ref(false)
const disabled = ref(false)
// 找图片  
const handlePictureCardPreview = (file: UploadFile) => {
  dialogImageUrl.value = file.url!
  dialogVisible.value = true
}
// 判断文件是否为图片
const isImage = (file: UploadFile) => {
  const acceptedImageTypes = ['image/gif', 'image/jpeg', 'image/png', 'image/svg+xml'];
  return acceptedImageTypes.includes(file.type);
};
// 上传
const handleDownload = (file: UploadFile) => {
  // 检验选择的文件是否为图片
  if (isImage(file.raw)) {
    // console.log("123", file.url);
    const formData = new FormData();
    formData.append('image', file.raw); // 将文件添加到 FormData
    updateEmployeeAvatar(formData).then((res) => {
      console.log(res);
      counterStore.userInfo.image = res.data;
      // console.log(counterStore.userInfo.image);
      
      ElMessage.success('上传成功');
    }).catch(() => {
      ElMessage.error('上传失败');
    });
  } else {
    ElMessage.error('请选择图片文件！');
  }
};

</script>



  
  